#!/usr/bin/python

import os
import tempfile
import subprocess
import sys
import traceback
import shutil
import re
import string
import time
import getopt

from shaggerbase import Shagger

#import stages
from util import TeeNoFile, allWorkingDiscs

import musicbrainz2.disc as mbdisc
from musicbrainzdata import MBalbum

from config import Config
from stages import Beepstage

class Modes:
    cd = 1
    nocd = 2
    auto = 3
    cont = 4
    cover = 5
    rework = 6
    lookup = 7
    

logfile = "shagger.%s.log" % time.strftime("%Y%m%d-%H%M.%S")
errfile = "shagger.%s.err" % time.strftime("%Y%m%d-%H%M.%S")

if not os.access(Config['logdir'], os.F_OK):
    #sledgehammer approach: can't read => dir doesn't exist.
    os.makedirs( Config['logdir'] )

tee=TeeNoFile(os.path.join(Config['logdir'], logfile))
tee2=TeeNoFile(os.path.join(Config['logdir'], errfile), "err")
print("Config: %s") % (Config)

try:
    opts, args = getopt.getopt(sys.argv[1:], "", ["cd", "nocd", "cover", "walk", "rework", "lookup"])
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    #usage() TODO
    sys.exit(2)



mode = Modes.auto
walk = False

print("Args:")
for (key, val) in opts:
    print("%s: %s" % (key,val))
    if (key=="--cd"):
        mode = Modes.cd
    if (key=="--nocd"):
        mode = Modes.auto
    if (key=="--cover"):
        mode = Modes.cover
    if (key=="--walk"):
        walk = True
    if (key=="--rework"):
        mode = Modes.rework
    if (key=="--lookup"):
        mode = Modes.lookup

if( len(args) == 0):
    args=["."]

print("%s" % args)

if mode==Modes.auto: #auto detect.
    try:
        mbdisc.readDisc()
        mode = Modes.cd
    except Exception:
        #oh well
        print("no cd")
        mode = Modes.cont

elif mode==Modes.cd:
    S = Shagger();
    S.workCD();
elif mode==Modes.cont:
    releases = allWorkingDiscs()
    for release in releases:
        S = Shagger()
        S.discid = release
        try:
            S.CheckCD()
            S.workCD()
        except Exception, why:             
            traceback.print_exc()           
            print ("Work on %s failed:\n%s" % (release, why) )
            Beepstage(S, Beepstage.fail)()
else:
    
    def doStuff(mode, path):
        print("Working %s" % path)
        try:
            S = Shagger()
            S.absdir = path

            if mode==Modes.cover:    
                S.CoverArtOnly()
            elif mode==Modes.rework:
                S.ReworkTags()
            elif mode==Modes.lookup:
                S.Lookup()
        except Exception, why:
            traceback.print_exc()           
            print ("Work on %s failed:\n%s" % (path, why) )
    
    for arg in args:
        if walk:
            for (path, dirs, files) in os.walk(arg):
                doStuff(mode, path)
        else:
            doStuff(mode, arg )


print("Done all possible work")
tee.close()
